package io.github.kimmking.kkconfig.spring;

import io.github.kimmking.kkconfig.value.SpringValueProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * Description for this class.
 *
 * @Author : kimmking(kimmking@apache.org)
 * @create 2024/4/19 00:41
 */
public class KKConfigRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata,
                                        BeanDefinitionRegistry registry) {
        System.out.println("KKConfigRegistrar.registerBeanDefinitions");
        registerBean(registry, PropertySourcesProcessor.class);
        registerBean(registry, SpringValueProcessor.class);
    }

    private static void registerBean(BeanDefinitionRegistry registry, Class<?> clazz) {

        Optional<String> first = Arrays.stream(registry.getBeanDefinitionNames())
                .filter(x -> Objects.equals(registry.getBeanDefinition(x)
                        .getBeanClassName(), clazz.getName())).findFirst();
        if(first.isEmpty()) {
            System.out.println("register " + clazz.getName());
            BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(clazz).getBeanDefinition();
            registry.registerBeanDefinition(clazz.getName(), beanDefinition);
        }
    }

}
